<template>
  <div>
    <van-nav-bar
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    >
    <template #title>
      TodoList
      <van-icon name="delete-o" size="20" @click="clear"/>
    </template>
      <template #right>
        <van-icon name="add-o" size="26" />
      </template>
    </van-nav-bar>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad">
            <todo-item
              v-for="item in list"
              :key="item.id"
              :item="item"
              @done="done"
              @refresh="onRefresh"
              />
        </van-list>
    </van-pull-refresh>
    <!-- <van-button class="clear" type="warning" block @click="clear">清空</van-button> -->
  </div>
</template>

<script>
import TodoItem from './components/TodoItem.vue'
export default {
  components: {
    TodoItem
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      refreshing: false,
      total: 40
    }
  },
  methods: {
    onLoad () {
      setTimeout(() => {
        console.log('lod')
        this.list = this.$store.state.app.todoList
        this.refreshing = false
        this.loading = false
        this.finished = true
      }, 500)
    },
    onRefresh () {
      // 清空列表数据
      this.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.onLoad()
    },
    onClickLeft () {
      this.$router.go(-1)
    },
    onClickRight () {
      this.$router.push({ name: 'AddTodo' })
    },
    done (item) {
      const find = this.list.find(x => x.id === item.id)
      find.done = true
      this.$store.dispatch('app/setTodoList', this.list)
    },
    clear () {
      this.$dialog.confirm({
        title: '警告',
        message: '是否清空所有?'
      }).then(() => {
        this.$store.dispatch('app/setTodoList', []).then(() => {
          this.onRefresh()
          this.$toast('已清空')
        })
      })
        .catch(() => {
          // on cancel
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.clear{
  position: absolute;
  bottom: 0;
  height: 50px !important;
}
</style>
